
package Type_1_arr.title5_P59;


//59. 螺旋矩阵 II
public class P59SpiralMatrixTwo1 {


    public static int[][] generateMatrix(int n) {
        int[][] nums = new int[n][n];

        int startX = 0, startY = 0;   //开始点和结束点

        int circleNum = 1;   // 记录当前的圈数

        int count = 1;//要填入的值

        //画圈
        while (circleNum <= n / 2) {   //执行的圈数

            //上
            for (int i = startX; i < n - circleNum; i++) {  //开始 结束条件为n-圈数
                nums[startX][i] = count++;
            }

            //右
            for (int i = startY; i < n - circleNum; i++) {
                nums[i][n - startY - 1] = count++;
            }

            //下
            for (int i = n - circleNum; i > startX; i--) {
                nums[n - startX - 1][i] = count++;
            }

            //左
            for (int i = n - circleNum; i > startY; i--) {
                nums[i][startY] = count++;
            }

            circleNum++; //下一圈
            startX++;   //下一个起始点
            startY++;   //下一个起始点
        }

        //特除处理中间元素
        if (n % 2 == 1) {
            nums[n / 2][n / 2] = count;
        }
        return nums;
    }

    public static void main(String[] args) {

        int target = 7;

        int[][] matrix = generateMatrix(target);


        printMatrix(matrix);
    }


    //用于打印
    public static void printMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            System.out.println("Empty matrix");
            return;
        }

        // 1. 找出每列的最大宽度
        int[] colWidths = new int[matrix[0].length];
        for (int[] row : matrix) {
            for (int j = 0; j < row.length; j++) {
                int length = String.valueOf(row[j]).length();
                if (length > colWidths[j]) {
                    colWidths[j] = length;
                }
            }
        }

        // 2. 格式化打印矩阵
        for (int[] row : matrix) {
            for (int j = 0; j < row.length; j++) {
                // 使用printf格式化输出，-表示左对齐
                System.out.printf("%-" + (colWidths[j] + 1) + "d", row[j]);
            }
            System.out.println(); // 换行
        }
        System.out.println("----------------------------------------------------"); // 换行
    }
}